package com.haizhi.crm.biz.task.message.engine;

import com.haizhi.crm.biz.builder.MsgSearchQoBuilder;
import com.haizhi.crm.biz.dao.MessageSourceDao;
import com.haizhi.crm.biz.model.MessageSourceDo;
import com.haizhi.crm.biz.task.message.model.ContextDto;
import com.haizhi.crm.biz.task.message.model.ProcessResp;
import com.haizhi.crm.biz.task.message.queue.Container;
import com.haizhi.crm.biz.task.message.transfer.MessageTransferFactory;
import com.haizhi.crm.biz.task.message.transfer.TransferService;
import com.haizhi.crm.biz.util.MessageUtil;
import com.haizhi.crm.search.model.SearchQo;
import com.haizhi.crm.search.model.SearchVo;
import com.haizhi.crm.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by wangshan on 2018/5/29.
 */
@Component
public class MessageProducer {

    @Autowired
    private SearchService searchService;

    @Autowired
    private MessageSourceDao messageSourceDao;

    public static final int PAGE_SIZE = 1000;

    /**
     * 生产者：查询昨天的消息并生产
     *
     * @param messageSourceDo
     * @return
     */
    public ProcessResp produce(MessageSourceDo messageSourceDo) {
        ProcessResp resp = new ProcessResp();
        Date nowDate = new Date();
        resp.setStartTime(nowDate);
        TransferService transferService = MessageTransferFactory.getTransfer(messageSourceDo.getMessageType());
        SearchQo searchQo = MsgSearchQoBuilder.get(messageSourceDo);
        SearchVo searchVo = searchService.search(searchQo);
        int totalLine = (int) searchVo.getSearchResp().getTotal();
        searchQo.setPageSize(PAGE_SIZE);
        for (int i = 1; i <= (totalLine / PAGE_SIZE) + 1; i++) {
            searchQo.setPageNo(i);
            searchVo = searchService.search(searchQo);
            List<Map<String, String>> datas = MessageUtil.toList(searchVo.getSearchResp().getData());
            for (Map<String, String> data : datas) {
                ContextDto contextDto = transferService.transfer(data);
                contextDto.setDatabases(messageSourceDo.getDatabase());
                contextDto.setMsgType(messageSourceDo.getMessageType());
                contextDto.setMsgSchema(messageSourceDo.getSchema());
                Container.put(contextDto);
            }
        }

        resp.setEndTime(new Date());
        resp.setMessageCount(totalLine);
        return resp;
    }

}
